// pages/start/start.js
import {
    ajaxPost,
    showToast,
}
from "../../utils/util.js";
import IMController from '../../IMJS/im'
let app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        canIUse: wx.canIUse("button.open-type.getUserInfo"),
        show: true,
        select: "",
        share_id: "",
        code: ""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let _this = this
        if (options.q !== undefined) {
            var scan_url = decodeURIComponent(options.q);
            let index = scan_url.indexOf("id") + 3;
            let newstring = scan_url.substring(index, scan_url.length);
            this.setData({
                share_id: newstring
            });
        }
        let token = wx.getStorageSync("token");
        if (!!token) {
            let data = {
                token: token
            };
            ajaxPost("/authuser/myInfo", data, function (res) {
                if (res.code == 0) {
                    let userInfo = res.data.user_info
                    if (userInfo.nickname == null) {
                        showToast('error', '请您先授权！', {
                            duration: 3000
                        })
                        _this.setData({
                            show: true
                        })
                        return;
                    }
                    if (userInfo.has_mobile == 0) {
                        showToast('text', '请继续授权,获取手机号');
                        _this.setData({
                            show: false
                        })
                        return;
                    }
                    if (userInfo.role == 2) {
                        wx.redirectTo({
                            url: "../student/home/home"
                        });
                    }
                    if (userInfo.role == 1) {
                        if (userInfo.is_set_userinfo == 0) {
                            wx.redirectTo({
                                url: "../enterprise/binding/binding"
                            });
                        } else {
                            wx.redirectTo({
                                url: "../enterprise/home/home"
                            });
                        }
                    }
                    _this.loginNIM()
                } else {
                    showToast('error', res.msg, {
                        duration: 3000
                    })
                }
            });
        }
    },
    /**
     * 获取授权个人信息 ----> 判断是否绑定，如果没有绑定-->绑定手机号
     *               ----> 否则去网易云登录
     */

    getUserInfo: function (e) {
        let _this = this;
        if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
            showToast('error', '拒绝授权将会无法使用树枝校招,请重新操作', {
                duration: 3000
            })
            return;
        }
        _this.setData({
            select: e.currentTarget.dataset.type
        })
        console.log('eeee', e);
        _this.userLogin(e.detail.encryptedData, e.detail.iv)

    },
    userLogin(encryptedData, iv) {
        let _this = this
        wx.login({
            success: function (res) {

                console.log('loginData', res);
                let data = {
                    code: res.code, // code  必须给
                    encryptedData: encryptedData, //密文串  必须给
                    iv: iv //加密初始量 必给
                };
                ajaxPost("/login/wxlogin", data, function (res) {
                    if (res.code == 0) {
                        wx.setStorageSync('token', res.data.token);
                        if (res.data.has_mobile == 0) {
                            showToast('text', '请继续授权,获取手机号');
                            _this.setData({
                                show: false
                            })
                        } else {
                            _this.loginNIM();
                        }
                    } else {
                        showToast('text', res.msg)
                    }
                });

            }
        });
    },
    /**
     * 获取手机号 ---> 网易云登录
     */
    getPhoneNumber(e) {
        if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
            showToast('error', '拒绝授权将会无法使用树枝校招,请重新操作', {
                duration: 3000
            })
            return;
        }
        if (!e.detail.encryptedData) return
        let _this = this;
        wx.checkSession({
            success() {
                _this.loginPhone(e.detail.encryptedData, e.detail.iv)
            },
            fail() {}
        })
    },

    /**
     * 获取手机号回调
     */

    loginPhone(encryptedData, iv) {
        let _this = this;
        let token = wx.getStorageSync("token");
        wx.login({
            success: function (res) {
                let data = {
                    token: token,
                    code: res.code,
                    encryptedData: encryptedData,
                    iv: iv
                };
                ajaxPost("/login/bindmobile", data, function (res) {
                    if (res.code == 0) {
                        _this.loginNIM()
                    } else {
                        showToast('text', res.msg)
                    }
                });

            }
        });
    },

    /**
     * 获取网易云账号 ----> 选择角色
     */
    loginNIM() {
        let _this = this;
        let data = {
            token: wx.getStorageSync("token"),
        };
        ajaxPost("/authuser/getwytoken", data, function (res) {
            if (res.code == 0) {
                app.globalData.wytoken = res.data.wytoken
                app.globalData.account = res.data.accid
                new IMController({
                    token: res.data.wytoken,
                    account: res.data.accid,
                })
                console.log('!!_this.data.select---->', !!_this.data.select);
                if (!!_this.data.select) {
                    _this.setUserType()
                }
            } else {
                showToast('text', res.msg)
            }
        });
    },
    /**
     * 选择角色   ---- > 进入页面
     */
    setUserType() {
        let _this = this
        let data = {
            token: wx.getStorageSync("token"),
            usertype: this.data.select == "enterprise" ? 4 : 3 //学生3 企业4
        };
        ajaxPost("/authuser/usertype", data, function (res) {
            if (res.code == 0) {
                if (_this.data.select == "student") {
                    wx.redirectTo({
                        url: "/pages/student/home/home"
                    });
                } else {
                    //企业
                    if (res.data.is_set_userinfo == 0) {
                        wx.redirectTo({
                            url: "/pages/enterprise/binding/binding"
                        });
                        return;
                    }
                    wx.redirectTo({
                        url: "/pages/enterprise/home/home"
                    });
                }
            } else {
                showToast('text', res.msg)
            }
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {}
});